//app.js
var common=require('common.js');
App({
  globalData: {
    appId: 'wx94f0205ba8c65a00',
    secret: '1213a5a6e4664c9a2825f004c36ab815',
    userInfo: null,
    openId: null,
    uid:0,
    album:[],
    historyScore:0,
    point:0,
    onePlayNeedPoint:500,
    oneShareGotPoint:1000,
    feeScale:2,
    backURL:'',
    containerPx:0,
    windowWidth:0,
    windowHeight:0,
  },
  userInfoReadyCallback:function(res){
    this.globalData.userInfo = res.userInfo;

  },
  getUserInfo:function(that){
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        that.globalData.userInfo = res.userInfo
        that.login();
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (that.userInfoReadyCallback) {
          that.userInfoReadyCallback(res)
        }
      }
    })
  },
  onLaunch: function (options) {
    var that = this;    
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    //获取硬件配置
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.pixelRatio)
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        that.globalData.windowWidth = res.windowWidth;
        that.globalData.windowHeight = res.windowHeight;
        var totalHeightPx = res.windowHeight;
        var rpxScale = 750 / res.windowWidth;

        var bottomRpx=230;
        var bottomPx = bottomRpx / rpxScale ;
        var containerPx = totalHeightPx - bottomPx;

        console.log('---',containerPx)
        that.globalData.containerPx = containerPx;

        console.log(rpxScale)
        console.log(res.windowHeight * rpxScale)

        console.log('version',res.version)
        console.log('platform',res.platform)
        console.log(res);
        console.log('--------------------');
      }
    })


    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          that.getUserInfo(that);
        }else{
/////////////////////////////////////////////
          var path = this.getPageUrl(options);
          if (path.indexOf('pages/index/index') >= 0) {
            return;
          }
          that.globalData.backURL=path;
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: "请到游戏首页登陆",
            complete: function (e) {
              wx.navigateTo({
                url: '/pages/index/index',
              })
            }
          })
        }
      }
    })
  },
  buildURL:function(str){
    return common.baseURL+str;
  }, 
  login: function (e) {
    var that=this;
	wx.showLoading({
		title:"正在登录游戏"
	})
    wx.login({
      success: function (res) {
        if (res.code) {
          //获取openId
          common.request({
            url: 'c=Game&a=getWXopenid',
            data: {
              js_code: res.code
            },
            method: 'GET',
            header: { 'content-type': 'application/json' },
            success: function (openIdRes) {
              if(openIdRes.status!=0){
                wx.showModal({
                  title: '错误',
                  content: '游戏登陆失败，请稍候再试',
                });
                return false;
              }
              console.info("登录成功返回的openId：" + openIdRes.data.openid);
              wx.setStorageSync('PHPSESSID', openIdRes.data.sessionId);
              that.globalData.openId = openIdRes.data.openid;


              // 判断openId是否获取成功
              if (openIdRes.data.openid != null & openIdRes.data.openid != undefined) {
                // 有一点需要注意 询问用户 是否授权 那提示 是这API发出的                 
                common.request({
                    url: 'c=Game&a=userLogin', 
                    data: { 
                      openId: that.globalData.openId,
                      headPic: that.globalData.userInfo.avatarUrl,
                      gender: that.globalData.userInfo.gender,
                      nickname: that.globalData.userInfo.nickName,
                    }, 
                    success: function (e) {
                      that.globalData.uid           = e.uid;
                      that.globalData.historyScore  = e.historyScore;
                      that.globalData.nickname      = e.nickname;
                      that.globalData.rank          = e.rank;
                      that.globalData.title          = e.title;					  
                      that.globalData.point         = e.point;
                      that.globalData.feeScale      = e.feeScale;
                      that.globalData.timeLimit     = e.timeLimit;
                    }, 
					complete:function(re){wx.hideLoading();},
                    method: "POST" 
                });

              } else {
                console.info("获取用户openId失败");
              }
            },
            fail: function (error) {
              console.info("获取用户openId失败");
              console.info(error);
			  wx.hideLoading();
            }
          })
        }
      }
    });
  },
  getPageUrl:function (options){
    var url = options.path    //当前页面url
    var options = options.query    //如果要获取url中所带的参数可以查看options
    //拼接url的参数
    var urlWithArgs = '/'+url + '?'
    for (var key in options) {
      var value = options[key]
      urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
    return urlWithArgs
  },

})